#!/bin/sh
# -*- tcl -*-
# The next line is executed by /bin/sh, but not tcl \
exec tclsh "$0" ${1+"$@"}

# Author: jiyin@redhat.com
# This is a test run monitor.

lappend ::auto_path $::env(HOME)/lib /usr/local/lib /usr/lib64 /usr/lib
package require yaml
package require tdom
package require sqlite3
package require runtestlib 1.1
package require getOpt 3.0
namespace import ::getOpt::* ::runtestlib::*

# global var
array set Opt {}
array set InvalidOpt {}
set Args [list]
set OptionList {
  "*Options:" {
	{help h}   {arg n	help {Print this usage}}
	{lsjob j}  {arg n	help {list the job}}
	{lsrun r}  {arg n	help {list the run}}
	{lsprogress p s} {}
	{lsres}    {arg n	help {list test res, for diff}}
	{db}       {arg y	help {db file}}
	jobchk     {arg n	help {TBD: check if the job was delete, but the status is not completed} hide {}}
  }
}

proc Usage {progname} {
	puts "Usage: $progname \[options\] \[pkg \[run\]\]"
	getUsage $::OptionList
}

# _parse_ argument
getOptions $OptionList $::argv Opt InvalidOpt Args
#puts "Debug: Args{$Args}"
#parray InvalidOpt
#parray Opt

if [info exist Opt(help)] {
	Usage $argv0
	exit 0
}

set dbfile "[dbroot]/testrun.db"
if {[info exist Opt(db)] && $Opt(db) != ""} {
	set dbfile $Opt(db)
}

sqlite3 db $dbfile
db timeout 6000
#===============================================================================
set pkgQ "select DISTINCT ti.pkgName from testinfo ti"
set pkgList [db eval $pkgQ]
set runList {}

foreach pkg $pkgList {
	set distroQ "
		select DISTINCT trun.distro_rgset
		from testrun trun
		join testinfo ti on
			trun.testid = ti.testid
		where ti.pkgName LIKE '$pkg' and trun.res != ''
	"
	foreach key [db eval $distroQ] {
		lappend runList "pkg {$pkg} run {$key}"
	}
	set runList [lsort -decreasing $runList]
}
#===============================================================================

set pkg [lindex $Args 0]
if {$pkg != {}} {
	set runList [lsearch -all -inline $runList "pkg {$pkg} *"]
}
set run [lindex $Args 1]
if {$run != {}} {
	set runList [lsearch -all -inline $runList "* run {$run}"]
}

if [info exist Opt(lsrun)] {
	foreach key $runList {
		set pkg [lindex $key 1]
		set run [lindex $key 3]
		puts "$pkg  '$run'"
	}
} elseif [info exist Opt(lsjob)] {
	foreach key $runList {
		set pkg [lindex $key 1]
		set run [lindex $key 3]
		set jobQ "
			select DISTINCT trun.jobid
			from testrun trun
			join testinfo ti on
				trun.testid = ti.testid
			where ti.pkgName LIKE '$pkg' and trun.distro_rgset LIKE '$run' and trun.res != '' and trun.jobid != ''
		"
		set jobList [db eval $jobQ]
		puts "\033\[1;34m$pkg '$run'\033\[0m:"
		puts "\t$jobList"
	}
} else {
	foreach key $runList {
		set pkg [lindex $key 1]
		set run [lindex $key 3]
		array unset count
		array set count {}
		set testQ "
		    select
			trun.distro_rgset as distro_rgset,
			trun.jobid as jobid,
			trun.testStat as tstat,
			trun.rstat as rstat,
			trun.res as res,
			trun.resdetail as resdetail,
			trun.abortedCnt as abortedCnt,
			trun.taskuri as taskuri,
			ti.test as test,
			trun.testid as testid,
			ti.pkgName as pkgName
		    from testrun trun
		    join testinfo ti on
			trun.testid = ti.testid
		    where ti.pkgName LIKE '$pkg' and trun.distro_rgset LIKE '$run' and trun.res != ''
		    ORDER by ti.test
		"
		db eval $testQ {
			set tdict [::yaml::yaml2dict $test]
			set tname [lindex $tdict 0]
			set tdict [lindex $tdict 1]
			set param {}
			set setup {}
			if [dict exist $tdict param] {
				set param [dict get $tdict param]
			}
			if [dict exist $tdict setup] {
				set setup [dict get $tdict setup]
			}

			set tinfo "$tname $param {$setup}"
			set shortcat "[file tail [file dirname $tinfo]]/[file tail $tinfo]"
			set tattr [lrange $test 1 end]

			set Stat $tstat
			if {$tstat == ""} {set Stat "nil"}
			if {$Stat == "completed"} {
				set Res "pass"
				if {[string map {Pass {} { } {}} $res] != ""} {
					set Res "notpass"
				}
				append Stat "-$Res"
			}
			if ![info exist count($Stat)] {set count($Stat) 0}
			set count($Stat) [incr count($Stat)]

			if ![info exist Opt(lsprogress)] {
				set testobj [format "{%s} {%s} {%s} {%s} {%s} %s {%s} %s" $distro_rgset $jobid $tstat $rstat $res $abortedCnt $shortcat $pkgName]
				if [info exist Opt(lsres)] {
					set testn [regsub {: {}} [regsub "attr:\[^\}]*\}(, )?" $test {}] {}]
					set testn [regsub {Attr:[^,]+,?} $testn {}]
					set taskuri [regsub -all {(^| )} $taskuri {&https://beaker.engineering.redhat.com/recipes/}]
					set resdetailn [regsub -all {\n} $resdetail {&  }]
					set resdetailn [string trim $resdetailn]
					set testobj [format "TEST_ID: %s\n%s\n%s\n  {%s}\n  %s\n" $testid $testn $taskuri $rstat $resdetailn]
				}
				puts "$testobj"
			}
		}
		if [info exist Opt(lsprogress)] {
			set sum 0
			foreach {stat cnt} [array get count] { set sum [incr sum $cnt] }

			puts "$pkgName '$distro_rgset'"
			foreach {stat cnt} [array get count] {
				puts [format "\t%-20s\t%4s\t%5.2f%%" "($stat)" $cnt [expr $cnt.0 / $sum * 100]]
			}
			puts ""
		}
	}
}
